<template>
  <div class="flow-attr">
    <el-form label-position="left" class="flow-config-attr" label-width="100px">
      <el-form-item label="网关名称">
        <el-input v-model="_value.name" class="input-attr" />
      </el-form-item>

      <el-form-item
        label="条件组关系"
        label-width="100px"
        label-position="left"
      >
        <el-switch
          v-model="_value.props.groupType"
          active-value="0"
          inactive-value="1"
          inactive-text="或"
          active-text="且"
        />
      </el-form-item>
      <el-form-item label="条件模式">
        <el-radio-group
          v-model="_value.props.conditionType"
          @change="methods.handleChangeconditionType"
        >
          <el-radio
            v-for="(item, index) in DIC_PROP.VAL_TYPE"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-radio-group>
        <el-tooltip placement="top">
          <template #content>若无法切换模式，请先清空条件组列表</template>
          <el-icon style="margin-left: 30px">
            <QuestionFilled />
          </el-icon>
        </el-tooltip>
      </el-form-item>
    </el-form>

    <div>
      <el-divider v-if="_value.props.conditionType === '0'"
        >组内条件配置</el-divider
      >
      <el-form
        label-position="left"
        class="flow-config-attr"
        label-width="100px"
      >
        <el-form-item
          label="组内条件关系"
          label-width="100px"
          label-position="left"
          v-if="_value.props.conditionType === '0'"
        >
          <el-switch
            v-model="condSimpleGroup.groupItemType"
            active-value="0"
            inactive-value="1"
            inactive-text="或"
            active-text="且"
          />
        </el-form-item>
        <el-form-item
          v-if="_value.props.conditionType === '1'"
          label="SpEL表达式"
        >
          <el-input
            v-model="condComplex.varKeyVal"
            class="input-attr"
            clearable
          />
          <el-tooltip placement="top">
            <template #content>{{
              PROP_CONST.TEXT_DESC.condSpELExplain
            }}</template>
            <el-icon style="margin-left: 10px">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </el-form-item>

        <el-form-item
          v-if="_value.props.conditionType === '2'"
          label="函数表达式"
        >
          <el-input
            v-model="condComplex.varKeyVal"
            class="input-attr"
            clearable
            @blur="methods.handleSaveComplexCondGroup"
          />
          <el-tooltip placement="top">
            <template #content>
              {{ PROP_CONST.TEXT_DESC.condMethodExplain1 }}
              <br />
              {{ PROP_CONST.TEXT_DESC.condMethodExplain2 }}
              <br />
              {{ PROP_CONST.TEXT_DESC.condMethodExplain3 }}
              <br />
              {{ PROP_CONST.TEXT_DESC.condMethodExplain4 }}
            </template>
            <el-icon style="margin-left: 10px">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
        </el-form-item>
        <div
          style="display: flex; justify-content: center; width: 100%"
          v-if="
            _value.props.conditionType === '2' ||
            _value.props.conditionType === '1'
          "
        >
          <el-button
            type="primary"
            round
            style="width: 160px; margin-top: 10px; margin-bottom: 10px"
            @click="methods.handleSaveComplexCondGroup"
          >
            保存条件
          </el-button>
        </div>
      </el-form>

      <div v-if="_value.props.conditionType === '2'" style="margin: 10px 13px">
        <span style="font-size: 14px; color: #409eff">
          注: 当前函数表达式的返回值为字符串 1 ( 满足 ) 或 0 ( 不满足 )
        </span>
      </div>

      <el-form
        v-if="_value.props.conditionType === '0'"
        ref="tableFormRef"
        class="form-table"
        inline-message
        :model="condSimpleGroup"
        :rules="condSimpleGroup.rules"
      >
        <el-table
          :data="condSimpleGroup.conditions"
          border
          style="width: 100%; margin-bottom: 10px"
          max-height="500"
        >
          <el-table-column type="index" label="操作" width="80">
            <template #header>
              <el-button
                icon="Plus"
                size="small"
                type="primary"
                circle
                @click="methods.handleAddSimpleConditionRow()"
              />
            </template>
            <template #default="scope">
              <el-button
                icon="Minus"
                size="small"
                type="danger"
                circle
                @click="
                  methods.handleDeleteSimpleConditionRow(
                    scope.$index,
                    scope.row
                  )
                "
              />
            </template>
          </el-table-column>

          <el-table-column
            prop="varKeyVal"
            label="表单字段"
            show-overflow-tooltip
          >
            <template #default="{ row, column, $index }">
              <el-form-item
                :prop="'conditions[' + $index + '].' + column.property"
                :rules="condSimpleGroup.rules.varKeyVal"
              >
                <el-select
                  v-model="row.varKeyVal"
                  clearable
                  filterable
                  @change="methods.handleSimpleItemChange(row)"
                >
                  <el-option
                    v-for="(item, index) in data.formItemList"
                    :key="index"
                    :label="getFormItemLabel(item)"
                    :value="getFormItemKey(item)"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="operator" label="运算符" show-overflow-tooltip>
            <template #default="{ row, column, $index }">
              <el-form-item
                :prop="'conditions[' + $index + '].' + column.property"
                :rules="condSimpleGroup.rules.operator"
              >
                <el-select v-model="row.operator" clearable>
                  <el-option
                    v-for="item in data.varValOperator"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="varVal" label="校验值" show-overflow-tooltip>
            <template #default="{ row, column, $index }">
              <el-form-item
                :prop="'conditions[' + $index + '].' + column.property"
                :rules="condSimpleGroup.rules.varVal"
              >
                <el-input v-model="row.varVal" clearable />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
        <div style="display: flex; justify-content: center; width: 100%">
          <el-button
            type="primary"
            round
            style="width: 160px; margin-top: 10px; margin-bottom: 10px"
            @click="methods.handleSaveSimpleConditionGroup"
          >
            保存条件
          </el-button>
        </div>
      </el-form>
    </div>

    <el-divider v-if="_value.props.conditionType === '0'">条件组</el-divider>
    <el-table
      v-if="_value.props.conditionType === '0'"
      :data="data.groups"
      border
      style="width: 100%"
      max-height="500"
      highlight-current-row
      @row-click="methods.handleClickGroupsRow"
    >
      <el-table-column type="index" label="操作" width="60">
        <template #default="scope">
          <el-button
            icon="Minus"
            size="small"
            type="danger"
            circle
            @click="methods.handleDeleteGroupsRow(scope.$index, scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="conditionType"
        label="条件模式"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-radio-group v-model="_value.props.conditionType" disabled>
            <el-radio
              v-for="(item, index) in DIC_PROP.VAL_TYPE"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column
        prop="groupItemType"
        label="组内条件关系"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-switch
            v-model="row.groupItemType"
            disabled
            active-value="0"
            inactive-value="1"
            inactive-text="或"
            active-text="且"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="conditionsCount"
        label="组内条件数量"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-tag>{{ row.conditions.length }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup lang="ts" name="FlowConRule">
import { validateNull } from "@/utils/validate";
import { DIC_PROP } from "@/flow/support/dict-prop";
import { queryFormItemList } from "@/api/flow/form/";
import { PROP_CONST } from "@/flow/support/prop-const";
import { createSerialItem } from "../ProcessNodes";
import { useMessage } from "@/hooks/message";
import { getRandNodeId } from "@/utils/process";
import { getFormItemLabel, getFormItemKey } from "@/views/design/form/FormItem";
import type { FormItemPerm } from "@/views/design/form/FormComponentMixin";

const props = defineProps({
  taskIndex: Number,
  defFlow: Object
});

const _value: any = defineModel();

const condComplex = reactive({
  varKeyVal: null
});

const condSimpleGroup = reactive({
  groupItemType: "0",
  conditions: [],
  rules: {
    varKeyVal: [
      {
        required: true,
        message: "请选择表单字段",
        trigger: "blur"
      }
    ],
    operator: [
      {
        required: true,
        message: "请选择运算符",
        trigger: "blur"
      }
    ],
    varVal: [
      {
        required: true,
        message: "请输入校验值",
        trigger: "blur"
      }
    ]
  }
});

const data = reactive({
  varValOperator: [],
  formItemList: [] as FormItemPerm[],
  groups: []
});

onMounted(() => {
  queryFormFieldData();
  data.varValOperator = DIC_PROP.OPERATOR;
  data.groups = _value.value.props.groups;
});

const queryFormFieldData = () => {
  queryFormItemList(props.defFlow.formId).then(res => {
    if (res.code === 200) {
      data.formItemList = res.data;
    }
  });
};

const methods = {
  handleSimpleItemChange(row) {
    if (row.varKeyVal && row.varKeyVal.includes(".")) {
      const varKeyValArray = row.varKeyVal.split(".");
      const dots = varKeyValArray.length - 1;
      if (dots === 2) {
        const tableKey = varKeyValArray[1];
        const columnKey = varKeyValArray[2];
        const formItem = data.formItemList.find(
          item => item.tableKey === tableKey && item.columnKey === columnKey
        );
        //默认1：1
        let mainSubRadio = "0";
        console.log(formItem);
        if (!formItem) {
          mainSubRadio = formItem.mainSubRadio;
        }
        //子表映射关系为1:N
        if (mainSubRadio === "1") {
          data.varValOperator = DIC_PROP.OPERATOR.slice(6);
        } else {
          data.varValOperator = DIC_PROP.OPERATOR;
        }
      } else {
        data.varValOperator = DIC_PROP.OPERATOR;
      }
    }
  },
  handleAddSimpleConditionRow() {
    const obj = {
      code: getRandNodeId(),
      varKeyVal: "",
      operator: "",
      varVal: ""
    };
    condSimpleGroup.conditions.push(obj);
    if (!data.formItemList || data.formItemList.length < 1) {
      queryFormFieldData();
    }
  },
  handleDeleteSimpleConditionRow(index: number, row: any) {
    condSimpleGroup.conditions.splice(index, 1);
  },
  handleSaveSimpleConditionGroup() {
    if (validateNull(condSimpleGroup.conditions)) {
      useMessage().warning("请先添加组内条件");
      return;
    }
    methods.saveSimpleCondition();
  },
  saveSimpleCondition() {
    const groupsTemp = _value.value.props.groups.filter(item => {
      return item.conditions && item.conditions.length > 0;
    });
    const groupsItem = createSerialItem();
    groupsItem.code = getRandNodeId();
    groupsItem.groupItemType = condSimpleGroup.groupItemType;
    groupsItem.conditions = condSimpleGroup.conditions;
    groupsTemp.push(groupsItem);
    condSimpleGroup.conditions = [];
    _value.value.props.groups = groupsTemp;
    data.groups = _value.value.props.groups;
  },
  handleDeleteGroupsRow(index: number, row: any) {
    _value.value.props.groups.splice(index, 1);
  },
  handleClickGroupsRow(row: any) {
    if (_value.value.props.conditionType === "0") {
      condSimpleGroup.groupItemType = row.groupItemType;
      condSimpleGroup.conditions = row.conditions;
    } else {
      condComplex.varKeyVal = row.conditions[0].varKeyVal;
    }
  },
  handleChangeconditionType(type?) {
    if (!type) {
      type = "0";
    }
    condSimpleGroup.conditions = [];
    condSimpleGroup.groupItemType = "0";
    condComplex.varKeyVal = null;
  },
  handleSaveComplexCondGroup() {
    const val = condComplex.varKeyVal;
    if (!val) {
      useMessage().warning("表达式为空");
      return;
    }
    if (
      _value.value.props.conditionType === DIC_PROP.VAL_TYPE[1].value &&
      val.indexOf("#") === -1
    ) {
      condComplex.varKeyVal = null;
      useMessage().warning("当选择SpEL模式时, SpEL表达式必须符合SpEL格式");
      return;
    } else if (
      _value.value.props.conditionType === DIC_PROP.VAL_TYPE[2].value &&
      val.indexOf("#") === -1
    ) {
      condComplex.varKeyVal = null;
      useMessage().warning("当选择专业模式时, 函数表达式必须符合规定的格式");
      return;
    }
    methods.saveComplexCondition(true);
  },
  saveComplexCondition(isSave: Boolean) {
    if (isSave) {
      _value.value.props.groups = [];
      const groupsItem = createSerialItem();
      groupsItem.code = getRandNodeId();
      groupsItem.groupItemType = null;
      groupsItem.conditions.push({
        code: getRandNodeId(),
        varKeyVal: condComplex.varKeyVal
      });
      _value.value.props.groups.push(groupsItem);
    }
    data.groups = _value.value.props.groups;
  }
};
</script>

<style lang="scss" scoped>
@use "@/assets/style/design/flow-attr.scss";
</style>
